<template>
  <div class="purchase-storage">
    <!-- 操作按钮和搜索区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="header-left">
          <el-button type="primary" @click="handleAdd">新建</el-button>
        </div>
        <div class="header-right">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入采购订单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="入库状态">
          <el-select v-model="searchForm.storageStatus" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" :value="null" />
            <el-option label="待入库" :value="0" />
            <el-option label="部分入库" :value="1" />
            <el-option label="全部入库" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="质检状态">
          <el-select v-model="searchForm.qcStatus" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" :value="null" />
            <el-option label="待质检" :value="0" />
            <el-option label="已质检" :value="1" />
            <el-option label="免检" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        ref="tableRef"
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="storageOrderNo" label="采购入库单号" width="180">
          <template #default="{ row }">
            <el-link type="primary">{{ row.storageOrderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="storageStatusDesc" label="入库状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.storageStatus)">
              {{ row.storageStatusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storageTime" label="入库时间" width="120">
          <template #default="{ row }">
            {{ row.storageTime ? formatDate(row.storageTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="入库人" width="100" />
        <el-table-column prop="supplierName" label="供应商" width="200">
          <template #default="{ row }">
            <el-link type="primary">{{ row.supplierName }} {{ row.supplierCode }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="qcStatusDesc" label="质检状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getQcStatusTagType(row.qcStatus)">
              {{ row.qcStatusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalQuantity" label="入库总数量" width="120" />
        <el-table-column prop="totalAmount" label="入库总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="quantityStock" label="已入库数量" width="120" />
        <el-table-column prop="amountEnteredIntoInventory" label="已入库金额" width="120" />
        <el-table-column prop="unqualifiedQuantity" label="不合格数量" width="120" />
        <el-table-column prop="rate" label="合格率" width="120" />

      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <div class="pagination-left">
          <el-checkbox v-model="selectAll" @change="toggleSelectAll">全选</el-checkbox>
          <el-button style="margin-left: 12px" @click="handleExport">导出</el-button>
        </div>
        <div class="pagination-center"></div>
        <div class="pagination-right">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
          :page-sizes="[5,10, 20, 50, 100]"
          :total="pagination.total"
            layout="prev, pager, next, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="入库人" prop="uId">
          <el-select
            v-model="form.uId"
            placeholder="请选择入库人"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="form.supplierId"
            placeholder="请选择供应商"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.value"
              :label="supplier.label"
              :value="supplier.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="质检状态" prop="qcStatus">
          <el-select v-model="form.qcStatus" placeholder="请选择质检状态" style="width: 100%">
            <el-option label="待质检" :value="0" />
            <el-option label="已质检" :value="1" />
            <el-option label="免检" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="入库时间" prop="storageTime">
          <el-date-picker
            v-model="form.storageTime"
            type="date"
            placeholder="请选择入库时间"
            format="yyyy-MM-dd"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="入库总数量" prop="totalQuantity">
          <el-input-number
            v-model="form.totalQuantity"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="入库总金额" prop="totalAmount">
          <el-input-number
            v-model="form.totalAmount"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="已入库数量">
          <el-input-number
            v-model="form.quantityStock"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="已入库金额">
          <el-input-number
            v-model="form.amountEnteredIntoInventory"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="不合格数量">
          <el-input-number
            v-model="form.unqualifiedQuantity"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="合格率">
          <el-input v-model="form.rate" placeholder="如：100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPurchaseStoragePage,
  addPurchaseStorage,
  getPurchaseStorageDetail,
  updatePurchaseStorage,
  deletePurchaseStorage,
  exportPurchaseStorage
} from '@/api/purchase/PurchaseStorage.js'
import { getUserListForDropdown, getSupplierList } from '@/api/purchase/User.js'
import http from '@/api/http'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  storageStatus: null,
  qcStatus: null,
  storageTime: null
})

// 用户选项数据
const userOptions = ref([])


// 供应商选项数据
const supplierOptions = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)
const tableRef = ref()
const selectAll = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentId = ref(null)

// 表单
const formRef = ref()
const form = reactive({
  uId: null,
  supplierId: null,
  qcStatus: null,
  storageTime: null,
  totalQuantity: null,
  totalAmount: null,
  quantityStock: 0,
  amountEnteredIntoInventory: 0,
  unqualifiedQuantity: 0,
  rate: '100%'
})

// 表单验证规则
const formRules = {
  uId: [{ required: true, message: '请选择入库人', trigger: 'change' }],
  supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  qcStatus: [{ required: true, message: '请选择质检状态', trigger: 'change' }],
  totalQuantity: [{ required: true, message: '请输入入库总数量', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '请输入入库总金额', trigger: 'blur' }]
}

// 获取数据
const getData = async () => {
  loading.value = true

  try {
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.size
    }

    console.log('查询参数：', params)

    const response = await http.post('/procurement/purchase/storage/page', params)
    const data = response.data

    if (data.code === 200) {
      const pageData = data.data

      console.log('=== 后端返回的分页数据 ===')
      console.log('pageData:', pageData)
      console.log('pageData.records:', pageData?.records)
      console.log('pageData.total:', pageData?.total)
      console.log('pageData.current:', pageData?.current)
      console.log('pageData.size:', pageData?.size)

      // 设置表格数据
      tableData.value = pageData?.records || []

      // 设置分页信息
      pagination.total = pageData?.total || 0
      pagination.current = pageData?.current || 1
      pagination.size = pageData?.size || 10

      console.log('=== 前端设置后的分页信息 ===')
      console.log('pagination.total:', pagination.total)
      console.log('pagination.current:', pagination.current)
      console.log('pagination.size:', pagination.size)
      console.log('tableData.length:', tableData.value.length)
      console.log('=== 分页信息设置完成 ===')

      // 如果total为0但有数据，强制设置total
      if (pagination.total === 0 && tableData.value.length > 0) {
        console.warn('检测到total为0但有数据，强制设置total为数据长度')
        pagination.total = tableData.value.length
      }
    } else {
      ElMessage.error(data.msg || '查询失败')
    }
  } catch (error) {
    console.error('查询错误：', error)
    ElMessage.error('查询失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    storageStatus: null,
    qcStatus: null,
    storageTime: null
  })
  pagination.current = 1
  getData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增采购入库'
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑采购入库'
  isEdit.value = true
  currentId.value = row.id
  loadFormData(row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  dialogTitle.value = '查看采购入库'
  isEdit.value = false
  currentId.value = row.id
  loadFormData(row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deletePurchaseStorage([row.id])
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    const response = await exportPurchaseStorage(searchForm)
    if (response.code === 200) {
      ElMessage.success('导出成功')
    } else {
      ElMessage.error(response.msg || '导出失败')
    }
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 数据转换和验证
    const submitData = {
      uId: form.uId,
      supplierId: form.supplierId,
      qcStatus: form.qcStatus,
      storageTime: form.storageTime ? new Date(form.storageTime).toISOString().split('T')[0] : null, // 确保日期格式正确
      totalQuantity: form.totalQuantity,
      totalAmount: form.totalAmount,
      quantityStock: form.quantityStock || 0,
      amountEnteredIntoInventory: Math.round(form.amountEnteredIntoInventory || 0), // 转换为整数
      unqualifiedQuantity: form.unqualifiedQuantity || 0,
      rate: form.rate || '100%'
    }

    console.log('提交数据：', submitData)

    const response = isEdit.value
      ? await updatePurchaseStorage(currentId.value, submitData)
      : await addPurchaseStorage(submitData)

    console.log('完整响应：', response)
    console.log('响应状态:', response.status)
    console.log('data.code:', response.data?.code)
    console.log('data.msg:', response.data?.msg)

    if (response.data?.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      dialogVisible.value = false
      getData()
    } else {
      ElMessage.error(response.data?.msg || response.msg || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交错误：', error)
    console.error('错误响应：', error.response?.data)
    console.error('错误状态码：', error.response?.status)

    let errorMessage = '操作失败：' + error.message
    if (error.response?.data?.msg) {
      errorMessage = '操作失败：' + error.response.data.msg
    } else if (error.response?.data?.message) {
      errorMessage = '操作失败：' + error.response.data.message
    }

    ElMessage.error(errorMessage)
  }
}

// 加载表单数据
const loadFormData = (row) => {
  Object.assign(form, {
    uId: row.uId,
    supplierId: row.supplierId,
    qcStatus: row.qcStatus,
    storageTime: row.storageTime,
    totalQuantity: row.totalQuantity,
    totalAmount: row.totalAmount,
    quantityStock: row.quantityStock || 0,
    amountEnteredIntoInventory: row.amountEnteredIntoInventory || 0,
    unqualifiedQuantity: row.unqualifiedQuantity || 0,
    rate: row.rate || '100%'
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    uId: null,
    supplierId: null,
    qcStatus: null,
    storageTime: null,
    totalQuantity: null,
    totalAmount: null,
    quantityStock: 0,
    amountEnteredIntoInventory: 0,
    unqualifiedQuantity: 0,
    rate: '100%'
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1 // 重置到第一页
  getData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  getData()
}

// 选择
const onSelectionChange = (rows) => {
  // no-op for now
}

const toggleSelectAll = (val) => {
  const table = tableRef.value
  if (!table) return
  if (val) {
    table.toggleAllSelection && table.toggleAllSelection()
  } else {
    table.clearSelection && table.clearSelection()
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'info'
    case 2: return 'success'
    default: return ''
  }
}

// 获取质检状态标签类型
const getQcStatusTagType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'info'
    default: return ''
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

// 初始化
// 加载用户数据
const loadUserData = async () => {
  try {
    console.log('开始加载用户数据')
    const response = await getUserListForDropdown()
    console.log('用户数据响应：', response)

    const payload = response?.data
    if (payload?.code === 200) {
      userOptions.value = payload.data || []
      console.log('用户选项数据：', userOptions.value)
    } else {
      const msg = payload?.msg || '未知错误'
      console.error('获取用户数据失败：', msg)
      ElMessage.error('获取用户数据失败：' + msg)
    }
  } catch (error) {
    console.error('加载用户数据错误：', error)
    console.error('错误详情：', error.response)
    ElMessage.error('加载用户数据失败：' + (error.response?.data?.msg || error.message || '网络错误'))
  }
}

// 加载供应商数据
const loadSupplierData = async () => {
  try {
    console.log('开始加载供应商数据')
    const response = await getSupplierList()
    console.log('供应商数据响应：', response)

    const payload = response?.data
    if (payload?.code === 200) {
      supplierOptions.value = payload.data || []
      console.log('供应商选项数据：', supplierOptions.value)
    } else {
      const msg = payload?.msg || '未知错误'
      console.error('获取供应商数据失败：', msg)
      ElMessage.error('获取供应商数据失败：' + msg)
    }
  } catch (error) {
    console.error('加载供应商数据错误：', error)
    console.error('错误详情：', error.response)
    ElMessage.error('加载供应商数据失败：' + (error.response?.data?.msg || error.message || '网络错误'))
  }
}

// 测试后端连接
const testBackendConnection = async () => {
  try {
    console.log('测试后端连接...')
    console.log('测试URL: /procurement/user/list')
    const response = await http.get('/procurement/user/list')
    console.log('后端连接测试成功：', response)
    return true
  } catch (error) {
    console.error('后端连接测试失败：', error)
    console.error('错误状态码：', error.response?.status)
    console.error('错误响应：', error.response?.data)
    console.error('完整错误对象：', error)
    return false
  }
}

onMounted(async () => {
  console.log('组件已挂载，开始加载数据')

  // 先测试后端连接
  const isBackendAvailable = await testBackendConnection()
  if (!isBackendAvailable) {
    ElMessage.error('后端服务不可用，请检查服务是否启动')
    return
  }

  loadUserData() // 加载用户数据
  loadSupplierData() // 加载供应商数据
  getData()
})
</script>

<style scoped>
.purchase-storage {
  padding: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-form {
  margin-bottom: 0;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-left {
  display: flex;
  align-items: center;
}

.pagination-center {
  display: flex;
  align-items: center;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

.pagination-right {
  display: flex;
  align-items: center;
}
</style>
